<?php
// +----------------------------------------------------------------------
// | 幕小铺
// +----------------------------------------------------------------------
// | 版权所有 2016~2020 幕小铺科技（大连）有限公司
// +----------------------------------------------------------------------
// | 2020/03/14
// +----------------------------------------------------------------------

namespace app\erp\admin;

use app\admin\controller\Admin;
use app\common\builder\ZBuilder;
/**
 * 商品管理
 * @package app\erp\admin
 */
class Goods extends Admin
{
    /**
     * 首页
     * @author shiqiang
     * @return mixed
     */
    public function index(){	
		cookie('__forward__', $_SERVER['REQUEST_URI']);
		
		$list = model('ErpGoodsClass', 'model') -> getClass();
		foreach($list as $key => $value){
			$goods_count = model('ErpGoods') -> where('goods_classid', $value['id']) -> count();
			$list[$key]['title_display'] = $value['title_display'] . '('. $goods_count .')';
		}
		
		$btn_video = [
			'title' => '查看商品',
			'icon'  => 'fa fa-fw fa-key',
			'class' => 'btn btn-xs btn-default',
			'href'  => url('index/index', ['classid' => '__id__', '_pop' => 1]),
		];
		
		$btn_access = [
			'title' => '添加',
			'icon'  => 'fa fa-fw fa-key',
			'class' => 'btn btn-xs btn-default',
			'href'  => url('add', ['pid' => '__id__']),
		];
		
		// 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table')
            ->setPageTitle('商品分类') // 设置页面标题
            ->setTableName('video_play_class') // 设置数据表名
            ->addColumns([ // 批量添加列
                ['id', 'id'],
                ['level', '级别'],
				['title_display', '分类标题(商品数量)', 'link', url('index/index', ['classid' => '__id__', '_pop' => 1]), '_blank', 'pop'],
				['code', '编码'],
				['class_img', '图片', 'picture'],
                ['sort', '排序','text.edit'],
                ['right_button', '操作', 'btn']
            ])
            ->addFilter(['report_status']) // 添加筛选
			->addTopButton('add', '', true) // 批量添加顶部按钮
			->addRightButton('custom', $btn_access, true) // 添加授权按钮
			->addRightButton('edit', '',true) // 批量添加右侧按钮
			->addRightButton('delete') // 批量添加右侧按钮
			->addRightButton('custom', $btn_video, true) // 查看视频
			->setRowList($list) // 设置表格数据,
            ->fetch(); // 渲染页面
    }
	
	/**
     * 商品列表
     * @author Naruto
     * @return mixed
     */
    public function list(){	
		cookie('__forward__', $_SERVER['REQUEST_URI']);
		
		// 获取筛选
		$map = $this->getMap();
		
		foreach ($map as $key => $value) {//根据 单品得条形码 查询出 商品
			if($value[0] == 'goods_code'){
				//unset($map[$key]);
				//查询出单品得数据
				$map_1 = [];
				$map_1[] = ['article_no', 'like', '%'.$value[2].'%'];
				$rel = model('ErpGoodsSku') -> where($map_1) -> column('goods_id');

				$map[$key] = [
					'id',
					'in',
					$rel,
				];
			}
		}

		//数据获取
        $data = input();
		$classtemp_id 	= isset($data['classtemp_id']) ? $data['classtemp_id'] : 0;
		$class_id 		= isset($data['class_id']) ? $data['class_id'] : 0;
		if($class_id > 0){
			$map_r = [];
			$map_r[] = ['path', ['like', $class_id.'-%'], ['like', '%-'.$class_id.'-%'], 'or'];
			$class_path = model('ErpGoodsClass') -> where($map_r) -> column('id');
//             print_r(model('ErpGoodsClass') -> getLastSql());
            $class_path[] = $class_id;
			$goods_id = model('ErpGoodsClassGl') -> where([['class_id', 'in', $class_path]]) -> column('goods_id');
			$map[] = ['id', 'in', $goods_id];
		}
		
		if($classtemp_id > 0){
			$map_r = [];
//			$map_r[] = ['path', 'like', '%'. $classtemp_id .'%'];
            $map_r[] = ['path', ['like', $classtemp_id.'-%'], ['like', '%-'.$classtemp_id.'-%'], 'or'];
			$classtemp_path	= model('ErpGoodsClassTemp') -> where($map_r) -> column('id');
            $classtemp_path[] = $classtemp_id;
			$map[] = ['goods_classtempid', 'in', $classtemp_path];
		}
		
		// 数据列表
		$data_list = model('erp/ErpGoods', 'model') -> where($map) -> order('create_time desc') -> paginate();
		
		$btn_goods_sku = [
			'title' => '单品列表',
			'icon'  => 'fa fa-fw fa-key',
			'class' => 'btn btn-xs btn-default',
			'href'  => url('Goods_sku/index', ['goods_id' => '__id__']),
		];

		$btn_guige = [
			'title' => '规格',
			'icon'  => 'fa fa-fw fa-key',
			'class' => 'btn btn-xs btn-default',
			'href'  => url('goods_specifications/index', ['goods_id' => '__id__']),
		];
		
		$edit_goods = [
			'title' => '编辑',
			'icon'  => 'fa fa-fw fa-key',
			'class' => 'btn btn-xs btn-default',
			'href'  => url('edit_goods', ['goods_id' => '__id__']),
		];
			
		// 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table')
            ->setPageTitle('商品列表') // 设置页面标题
            //->setTableName('video_play_class') // 设置数据表名
            ->addColumns([ // 批量添加列
				['id', 'id'],
				//['goods_name', '缩略图'],
                ['goods_name', '商品名称', 'text.edit'],
				//['goods_code', '商品编码', 'text.edit'],
				['unit_measurement', '计量单位', 'text.edit'],
				['is_single_specification', '是否统一规格','status', '', [0 => '多规格:default', 1 => '统一规格:default']],
                ['right_button', '操作', 'btn']
            ])
            ->setSearchArea([
                ['text', 'goods_name', '商品名称', 'like'],
                ['text', 'goods_code', '国际条形码', 'like'],
				['daterange', 'create_time', '创建时间'],
                ['select', 'is_single_specification', '是否统一规格', '', '', [0 => '多规格', 1 => '统一规格']],
            ])
			->addRightButton('custom', ['title' => '详情', 'href' => url('details',['goods_id'=>'__id__'])],true) // 详情
			// ->addRightButton('edit_goods', $edit_goods, true) // 批量添加右侧按钮
			->addRightButton('edit_goods', $edit_goods) // 批量添加右侧按钮
			->addRightButton('btn_guige', $btn_guige, true) // 批量添加右侧按钮
			->addRightButton('sku', $btn_goods_sku, true) // 批量添加右侧按钮
			->replaceRightButton(['is_single_specification' => 1], '', ['btn_guige'])
			->addRightButton('delete') // 批量添加右侧按钮
			->setRowList($data_list) // 设置表格数据
            ->fetch(); // 渲染页面
	}
	
	/**
     * 编辑
     * @author shiqiang <976162041@qq.com>
     * @return mixed
     * @throws \think\Exception
     */
    public function edit_goods($goods_id = ''){
		$unit_arr = ['件','套','瓶','桶','袋','箱','包','双','套','打','公斤','千克'];
		// 保存数据
		if ($this->request->isPost()) {
			//数据接收
			$data = $this->request->post('', null, 'trim');

			//数据校验
			if(!isset($data['goods_name']) || $data['goods_name'] == '') $this->error('请输入商品名称');
			if(!isset($data['goods_code']) || $data['goods_code'] == '') $this->error('请输入商品编码');
			if($data['unit'] == 0){
				if(!isset($data['unit_measurement1']) || $data['unit_measurement1'] == ''){
					$this->error('请选择计量单位');
				}
			} 
			if($data['unit'] == 1){
				if(!isset($data['unit_measurement2']) || $data['unit_measurement2'] == ''){
					$this->error('请输入计量单位');
				}
			} 
			if(!isset($data['pic1'])|| empty($data['pic1'])) $this->error('请上传产品缩略图');
			if(!isset($data['pic2'])|| empty($data['pic2'])) $this->error('请上传产品详情图');
			if(!isset($data['brand_id']) || $data['brand_id'] == '') $this->error('请选择品牌');
			if(!isset($data['class_id_arr']) || $data['class_id_arr'] == '') $this->error('请选择商品分类');
			if(!isset($data['supplier_id']) || $data['supplier_id'] == '') $this->error('请选择供应商类');
			// if(!isset($data['parameter']) || empty($data['parameter'])) $this->error('请选择商品参数');
			
			//图片上传
			$img_id_arr1 = $img_id_arr2 = [];
			if($data['pic1']){
				$pic_arr = explode(',', $data['pic1']);
				$cover_video_arr = [];
				foreach ($pic_arr as $key => $value) {
					if(is_numeric($value)){
						//获取本地路径
						$avatar_url = model('admin/Attachment') -> getFilePath($value, 1);
						//获取本地附件信息
						$attachment_info = model('admin/Attachment') -> find($value);
						//上传OSS
						$rel = controller('common/Osslogic', 'logic') -> uploadFile($avatar_url, 'goods_suoluetu/'.$avatar_url);
						$avatar_url_rel = $rel['data']['info']['url'];

						$data_list = [
							'uid' => 1,
							'img_url' => $avatar_url_rel,
							'width'	=> $attachment_info['width'],
							'height'	=> $attachment_info['height'],
							'create_time' => time(),
							'update_time' => time(),
						];
						$cover_video_arr[] = model('ErpGoodsImgs') -> insertGetId($data_list);					
					}else{
						foreach(json_decode($data['coverimgArr'], true) as $k => $v){
							if($value == $v['img_url']){
								$cover_video_arr[] = $v['id'];
							}
						}
					}
				}
			}
			if($data['pic2']){
				$pic_arr = explode(',', $data['pic2']);
				$details_arr = [];
				foreach ($pic_arr as $key => $value) {
					if(is_numeric($value)){
						//获取本地路径
						$avatar_url = model('admin/Attachment') -> getFilePath($value, 1);
						//获取本地附件信息
						$attachment_info = model('admin/Attachment') -> find($value);
						//上传OSS
						$rel = controller('common/Osslogic', 'logic') -> uploadFile($avatar_url, 'goods_suoluetu/'.$avatar_url);
						$avatar_url_rel = $rel['data']['info']['url'];

						$data_list = [
							'uid' => 1,
							'img_url' => $avatar_url_rel,
							'width'	=> $attachment_info['width'],
							'height'	=> $attachment_info['height'],
							'create_time' => time(),
							'update_time' => time(),
						];
						$details_arr[] = model('ErpGoodsImgs') -> insertGetId($data_list);
					}else{
						foreach(json_decode($data['detailsimgArr'], true) as $k => $v){
							if($value == $v['img_url']){
								$details_arr[] = $v['id'];
							}
						}
					}
				}
			}

			$parameter =[];
			//dump($data['parameter']);
			$data['parameter_list'] = isset($data['parameter_list']) ? $data['parameter_list'] : [];
			foreach ($data['parameter_list'] as $key => $value) {
				$rel_temp = explode('-', $value);

				$parameter[] = [
					'parameter_id' => $rel_temp[0],
					'attribute_id' => $rel_temp[1],
				];
			}

			//数据规整
			$user_id = 1;
			$goods_name = $data['goods_name'];
			$goods_code = $data['goods_code'];
			$brand_id = $data['brand_id'];
			$supplier_id = $data['supplier_id'];
			$goods_classid = array($data['class_id_arr']);
			$unit_measurement = $data['unit'] == 1 ? $data['unit_measurement2'] : $unit_arr[$data['unit_measurement1']];


			$parameter = $parameter;
			$single_item = [];
			$specifications = [];
			$is_single_specification = $data['is_single_specification'];
			$goods_classtempid = $data['goods_classtempid'];


			//数据插入
			$rel = controller('Goodslogic', 'logic')-> goods_edit($goods_id, $user_id, $goods_name, $goods_code, $brand_id, $supplier_id, $goods_classid, $cover_video_arr, $unit_measurement, $parameter, $single_item, $is_single_specification, $specifications, $details_arr, $goods_classtempid);
			
			if($rel['code'] == 200){
				$this -> success('编辑成功', url('list'));
			}
			//dump($rel);die;

		}
		
		$goods_info = model('ErpGoods') -> find($goods_id);
		
		$map = [];
		$brand_list_rel = [];
		$brand_list = model('ErpGoodsBrand') -> select();//品牌
		foreach ($brand_list as $key => $value) {
			$brand_list_rel[$value['id']] = $value['title'];
		}

		$class_list = model('ErpGoodsClass') -> getClass();//分类
		foreach ($class_list as $key => $value) {
			$class_list_rel[$value['id']] = $value['title_display'];
		}

		$supplier_list = model('ErpSupplier') -> select();//规格
		$supplier_list_rel = [];
		foreach ($supplier_list as $key => $value) {
			$supplier_list_rel[$value['id']] = $value['title'];
		}
		$goods_classtempid = $goods_info['goods_classtempid'];//类目
		$map = [];
		$map['id'] = $goods_classtempid;
		$goods_classtemptitle = model('ErpGoodsClassTemp')->where($map) -> value('title');

		//参数处理
		$map = [];
		$map['classtemp_id'] = $goods_classtempid;
		$par_list = model('erp/ErpGoodsClasstempParameter')->where($map) -> select();//dump($par_list);//die;
		//dump($par_list);die;
		$groups = [];
		foreach ($par_list as $key => $value) {
			$list = [];
			foreach ($value->get_erp_parameter->get_erp_parameter_attribute as $key1 => $value1) {
				$list[$value->get_erp_parameter->id.'-'.$value1['id']] = $value1->title;
			}
			$groups[$value->get_erp_parameter->title] = $list;
		}
		//规格处理
		$map = [];
		$map['classtemp_id'] = $goods_classtempid;
		$par_list = model('erp/ErpGoodsClasstempSpecifications')->where($map) -> select();
		//dump($par_list->toArray());
		if(empty($par_list->toArray())){
			$map = [];
			$map['classtemp_id'] = 75;
			$par_list = model('erp/ErpGoodsClasstempSpecifications')->where($map) -> select();
		}
		foreach ($par_list as $key => $value) {
			$att_m_list = [];
			foreach ($value -> get_erp_specifications->get_erp_specifications_attribute as $key1 => $value1) {
				$att_m_list[$value1 -> id.'-'.$value1 -> title.'-'.$value->id.'-'.$value -> get_erp_specifications -> title] = $value1 -> title;
			}

			$speci_list[] = [
				'title' 		=> $value -> get_erp_specifications -> title,
				'att_list'		=> $att_m_list,

			];

			if($key == 1) break;

		}
		//缩略图
		$coverlistimgArr = [];
		$coverlistimgArr_id = [];
		$coverlist = controller('erp/GoodsCoverimglogic', 'logic') -> getCoverImgListByGoodsid($goods_id);//dump($params);
		if($coverlist['code'] == 200){
			foreach($coverlist['data'] as $key => $value){
				if($value['img_url'] != ''){
					$coverlistimgArr_id[$key]['id'] 	 = $value['id'];
					$coverlistimgArr_id[$key]['img_url'] = $value['img_url'];
					$coverlistimgArr[] 	  = $value['img_url'];
				}
			}
		}
		//详情图
		$detailsImgArr_id = [];
		$detailsImgArr = [];
		$detailslist = controller('erp/GoodsDetailslogic', 'logic') -> getListByGoodsid($goods_id);//dump($params);
		if($detailslist['code'] == 200){
			foreach($detailslist['data'] as $key => $value){
				if($value['img_url'] != ''){
					$detailsImgArr_id[$key]['id'] 	 	= $value['id'];
					$detailsImgArr_id[$key]['img_url'] 	= $value['img_url'];
					$detailsImgArr[] 	= $value['img_url'];
				}
			}
		}
		$goods_info['goods_classtemptitle'] = $goods_classtemptitle;
		$goods_info['guige'] 			 = $goods_info['is_single_specification'];
		$goods_info['unit_measurement2'] = $goods_info['unit_measurement'];
		// $goods_info['class_id_arr'] 	 = model('ErpGoodsClassGl') -> where([['goods_id', '=', $goods_id]]) -> column('class_id');
		$goods_info['class_id_arr'] 	 = model('ErpGoodsClassGl') -> where([['goods_id', '=', $goods_id]]) -> find() -> class_id;
		$goods_info['pic1'] 	 	 	 = implode(',', $coverlistimgArr);
		$goods_info['pic2'] 	 	 	 = implode(',', $detailsImgArr);
		$goods_info['coverimgArr']		 = json_encode($coverlistimgArr_id);
		$goods_info['detailsimgArr']  	 = json_encode($detailsImgArr_id);
		//dump($groups);die;
		$parameter_list = model('ErpGoodsParameter') -> where([['goods_id', '=', $goods_id]]) -> column('parameter_id,attribute_id');
		$goods_parameter = [];
		foreach($parameter_list as $key => $value){
			$goods_parameter[] = $key . '-' . $value;
		}
		
		//根据类目添加参数
		return ZBuilder::make('form')
			->setPageTitle('编辑商品')
			->addStatic('goods_classtemptitle', '类目')
			->addText('goods_name', '商品标题[:请输入标题]')
			->addText('goods_code', '商品编码[:请输入编码]')

			->addRadio('unit', '计量单位', '', ['0' => '预置单位', '1' => '自定义单位'], 1)

			->setTrigger('unit', 1, 'unit_measurement2')
			->setTrigger('unit', 0, 'unit_measurement1')
			->addSelect('unit_measurement1', '选择计量单位[:选择计量单位]', '请选择计量单位', $unit_arr)
			->addText('unit_measurement2', '输入计量单位[:请输入计量单位]')

			->addSelect('brand_id', '品牌', '请选择品牌', $brand_list_rel)
			// ->addSelect('class_id_arr', '选择商品分类', '请选择商品分类', $class_list_rel, '', 'multiple')
			->addLinkages('class_id_arr', '选择商品分类', '', 'erp_goods_class', 3, '', ['name' => 'title'])
			
			->addSelect('supplier_id', '供应商', '请选择供应商', $supplier_list_rel)

			->addImages_oss('pic1', '产品缩略图', '', '', '', '', '', ['size' => '500,500'])
			->addImages_oss('pic2', '产品详情图', '', '', '', '', '', ['size' => '500,500'])

			->addFormItems([ // 批量添加表单项
				['selectGroup', 'parameter_list', '商品参数', '', $groups, $goods_parameter, 'multiple'],
				['hidden', 'is_single_specification'],
				['hidden', 'coverimgArr'],
				['hidden', 'detailsimgArr'],
				['hidden', 'goods_classtempid'],
			])
			
			->setFormData($goods_info)
			//->isAjax(false)
            ->fetch();
	}

	/**
     * 新增
     * @author shiqiang <976162041@qq.com>
     * @return mixed
     * @throws \think\Exception
     */
    public function add_goods($pid = ''){
		$unit_arr = ['件','套','瓶','桶','袋','箱','包','双','套','打','公斤','千克'];
		// 保存数据
		if ($this->request->isPost()) {
			//数据接收
			$data = $this->request->post('', null, 'trim');
			//数据校验
			if(!isset($data['goods_name']) || $data['goods_name'] == '') $this->error('请输入商品名称');
			if(!isset($data['goods_code']) || $data['goods_code'] == '') $this->error('请输入商品编码');
			if($data['unit'] == 0){//dump($data['unit_measurement1']);
				if(!isset($data['unit_measurement1']) || $data['unit_measurement1'] == ''){
					$this->error('请选择计量单位');
				}
			} 
			if($data['unit'] == 1){
				if(!isset($data['unit_measurement2']) || $data['unit_measurement2'] == ''){
					$this->error('请输入计量单位');
				}
			} 
			
			if(!isset($data['pic1'])|| empty($data['pic1'])) $this->error('请上传产品缩略图');
			if(!isset($data['pic2'])|| empty($data['pic2'])) $this->error('请上传产品详情图');
			if(!isset($data['brand_id']) || $data['brand_id'] == '') $this->error('请选择品牌');
			if(!isset($data['class_id_arr']) || $data['class_id_arr'] == '') $this->error('请选择商品分类');
			if(!isset($data['supplier_id']) || $data['supplier_id'] == '') $this->error('请选择供应商类');
			// if(!isset($data['parameter']) || empty($data['parameter'])) $this->error('请选择商品参数');
			if($data['guige'] == 0 && empty($data['specifications1']) && empty($data['specifications2'])) $this->error('请选择规格');
			if($data['guige'] == 1 && $data['goods_huohao'] == '') $this->error('请输入国际条形码');
			//if($data['guige'] == 1 && $data['goods_zhongliang'] == '') $this->error('请输入重量');
			//if($data['guige'] == 1 && $data['goods_tiji'] == '') $this->error('请输入体积');
			if($data['guige'] == 1 && $data['goods_jiage'] == '') $this->error('请输入价格');
			if($data['guige'] == 1 && $data['purchase_price'] == '') $this->error('请输入价格');
			
			//数据校验
			//dump($data);

			//数据处理

			//图片上传
			$img_id_arr1 = $img_id_arr2 = [];
			if($data['pic1']){
				$pic_arr = explode(',', $data['pic1']);
				foreach ($pic_arr as $key => $value) {
					//获取本地路径
					$avatar_url = model('admin/Attachment') -> getFilePath($value, 1);
					//获取本地附件信息
					$attachment_info = model('admin/Attachment') -> find($value);
					//上传OSS
					$rel = controller('common/Osslogic', 'logic') -> uploadFile($avatar_url, 'goods_suoluetu/'.$avatar_url);
					//if($rel['code'] != 200) //$this->error('头像上传失败');
					$avatar_url_rel = $rel['data']['info']['url'];

					$data_list = [
						'uid' => 1,
						'img_url' => $avatar_url_rel,
						'width'	=> $attachment_info['width'],
						'height'	=> $attachment_info['height'],
						'create_time' => time(),
						'update_time' => time(),
					];
					$cover_video_arr[] = model('ErpGoodsImgs') -> insertGetId($data_list);
				}
			}
			if($data['pic2']){
				$pic_arr = explode(',', $data['pic2']);
				foreach ($pic_arr as $key => $value) {
					//获取本地路径
					$avatar_url = model('admin/Attachment') -> getFilePath($value, 1);
					//获取本地附件信息
					$attachment_info = model('admin/Attachment') -> find($value);
					//上传OSS
					$rel = controller('common/Osslogic', 'logic') -> uploadFile($avatar_url, 'goods_suoluetu/'.$avatar_url);
					//if($rel['code'] != 200) //$this->error('头像上传失败');
					$avatar_url_rel = $rel['data']['info']['url'];

					$data_list = [
						'uid' => 1,
						'img_url' => $avatar_url_rel,
						'width'	=> $attachment_info['width'],
						'height'	=> $attachment_info['height'],
						'create_time' => time(),
						'update_time' => time(),
					];
					$details_arr[] = model('ErpGoodsImgs') -> insertGetId($data_list);
				}
			}

			$parameter =[];
			//dump($data['parameter']);
			$data['parameter'] = isset($data['parameter']) ? $data['parameter'] : [];
			foreach ($data['parameter'] as $key => $value) {
				$rel_temp = explode('-', $value);

				$parameter[] = [
					'parameter_id' => $rel_temp[0],
					'attribute_id' => $rel_temp[1],
				];
			}
			if($data['guige'] == 1){//单规格
				$single_item = [//单品信息
					[

						'goods_specifications'          => '统一规格',

						'specifications1_attribute_id'  => 0,
						'specifications1_attribute'  => '空',

						'specifications2_attribute_id'  => 0,
						'specifications2_attribute'  => '空',

						'article_no'                => $data['goods_huohao'],
						'weight'                    => $data['goods_zhongliang'],
						'volume'                    => $data['goods_tiji'],
						'price'                     => $data['goods_jiage'],
						'purchase_price'            => $data['purchase_price'],
						'sku_status'                => $data['sku_status'],
					],
				];
				$specifications = [];
			}else{
				//判断一下规格选择了几个
				if(isset($data['specifications1']) && isset($data['specifications2'])){
					foreach ($data['specifications1'] as $key => $value) {
						$value_array =  explode('-', $value);
						$attribute_2 = [];
						foreach ($data['specifications2'] as $key1 => $value1) {
							$value1_array =  explode('-', $value1);
							$single_item[] = [

									'goods_specifications'          => $value_array[1].' '.$value1_array[1],

									'specifications1_attribute_id'  => $value_array[0],
									'specifications1_attribute'  	=> $value_array[1],

									'specifications2_attribute_id'  => $value1_array[0],
									'specifications2_attribute'  	=> $value1_array[1],

									'article_no'                => $data['goods_huohao'],
									'weight'                    => $data['goods_zhongliang'],
									'volume'                    => $data['goods_tiji'],
									'price'                     => $data['goods_jiage'],
									'purchase_price'            => $data['purchase_price'],
									'sku_status'                => 2,
							];

							$attribute_2[] = [
								'attribute_id' 		=> $value1_array[0],
								'attribute_title'   => $value1_array[1],
							];

							$specifications_m[$value1_array[2]] = [
								'specifications_id' 	=> $value1_array[2],
								'specifications_title'	=> $value1_array[3],
								'attribute'				=> $attribute_2
							];

						}

						$attribute_1[] = [
							'attribute_id' 		=> $value_array[0],
							'attribute_title'   => $value_array[1],
						];

						$specifications_m[$value_array[2]] = [
							'specifications_id' 	=> $value_array[2],
							'specifications_title'	=> $value_array[3],
							'attribute'				=> $attribute_1
						];
					}

					foreach ($specifications_m as $key => $value) {
						$specifications[] = $value;
					}

				}else if(isset($data['specifications1']) || isset($data['specifications2'])){
					if(isset($data['specifications1'])){
						$data_arr = $data['specifications1'];
					}
					if(isset($data['specifications2'])){
						$data_arr = $data['specifications2'];
					}

					foreach ($data_arr as $key => $value) {
						$value_array =  explode('-', $value);

						$single_item[] = [

							'goods_specifications'          => $value_array[1],

							'specifications1_attribute_id'  => $value_array[0],
							'specifications1_attribute'  	=> $value_array[1],

							'specifications2_attribute_id'  => 0,
							'specifications2_attribute'  	=> '空',

							'article_no'                => $data['goods_huohao'],
							'weight'                    => $data['goods_zhongliang'],
							'volume'                    => $data['goods_tiji'],
							'price'                     => $data['goods_jiage'],
							'purchase_price'            => $data['purchase_price'],
							'sku_status'                => 2,
					];
						$attribute_1[] = [
							'attribute_id' 		=> $value_array[0],
							'attribute_title'   => $value_array[1],
						];

						$specifications_m[$value_array[2]] = [
							'specifications_id' 	=> $value_array[2],
							'specifications_title'	=> $value_array[3],
							'attribute'				=> $attribute_1
						];
					}

					foreach ($specifications_m as $key => $value) {
						$specifications[] = $value;
					}
				}
			}

			//数据规整
			$user_id = 1;
			$goods_name = $data['goods_name'];
			$goods_code = $data['goods_code'];
			$brand_id = $data['brand_id'];
			$supplier_id = $data['supplier_id'];
			$goods_classid = (array)$data['class_id_arr'];//dump($goods_classid);
			$unit_measurement = $data['unit'] == 1 ? $data['unit_measurement2'] : $unit_arr[$data['unit_measurement1']];


			$parameter = $parameter;
			$single_item = $single_item;
			$is_single_specification = $data['guige'];
			$goods_classtempid = $data['goods_classtempid'];




			//数据插入
			$rel = controller('Goodslogic', 'logic')
			-> goods_add($user_id, $goods_name, $goods_code, $brand_id, $supplier_id, $goods_classid, $cover_video_arr, $unit_measurement,
			$parameter, $single_item, $is_single_specification, $specifications, $details_arr, $goods_classtempid);
			//dump($rel);

			if($rel['code'] == 200){
				$this -> success('添加成功', url('list'));
			}else{
				$this -> error('添加失败');
			}
			//dump($rel);die;

		}

		$map = [];
		$brand_list_rel = [];
		$brand_list = model('ErpGoodsBrand') -> select();
		foreach ($brand_list as $key => $value) {
			$brand_list_rel[$value['id']] = $value['title'];
		}

		// $class_list = model('ErpGoodsClass') -> getClass();
		// foreach ($class_list as $key => $value) {
			// $class_list_rel[$value['id']] = $value['title_display'];
		// }

		$supplier_list = model('ErpSupplier') -> select();
		$supplier_list_rel=[];
		foreach ($supplier_list as $key => $value) {
			$supplier_list_rel[$value['id']] = $value['title'];
		}
		$goods_classtempid = input('goods_classtempid');
		$map = [];
		$map['id'] = $goods_classtempid;
		$goods_classtemptitle = model('ErpGoodsClassTemp')->where($map) -> value('title');

		//参数处理
		$map = [];
		$map['classtemp_id'] = $goods_classtempid;
		$par_list = model('erp/ErpGoodsClasstempParameter')->where($map) -> select();//dump($par_list);//die;
		
		$groups = [];
		foreach ($par_list as $key => $value) {
			$list = [];
			foreach ($value->get_erp_parameter->get_erp_parameter_attribute as $key1 => $value1) {
				$list[$value->get_erp_parameter->id.'-'.$value1['id']] = $value1->title;
			}
			$groups[$value->get_erp_parameter->title] = $list;
		}
		//规格处理
		$map = [];
		$map['classtemp_id'] = $goods_classtempid;
		$par_list = model('erp/ErpGoodsClasstempSpecifications')->where($map) -> select();
		//dump($par_list->toArray());
		if(empty($par_list->toArray())){
			$map = [];
			$map['classtemp_id'] = 75;
			$par_list = model('erp/ErpGoodsClasstempSpecifications')->where($map) -> select();
		}
		foreach ($par_list as $key => $value) {
			$att_m_list = [];
			foreach ($value -> get_erp_specifications->get_erp_specifications_attribute as $key1 => $value1) {
				$att_m_list[$value1 -> id.'-'.$value1 -> title.'-'.$value->id.'-'.$value -> get_erp_specifications -> title] = $value1 -> title;
			}

			$speci_list[] = [
				'title' 		=> $value -> get_erp_specifications -> title,
				'att_list'		=> $att_m_list,

			];

			if($key == 1) break;

		}
		//dump($speci_list);die;
		//根据类目添加参数
		return ZBuilder::make('form')
			->setPageTitle('添加商品')
			->addStatic('goods_classtempid', '类目', '', $goods_classtemptitle, input('goods_classtempid'))
			->addText('goods_name', '商品标题[:请输入标题]')
			->addText('goods_code', '商品编码[:请输入编码]')

			->addRadio('unit', '计量单位', '', ['0' => '预置单位', '1' => '自定义单位'], 0)

			->setTrigger('unit', 1, 'unit_measurement2')
			->setTrigger('unit', 0, 'unit_measurement1')
			->addSelect('unit_measurement1', '选择计量单位[:选择计量单位]', '请选择计量单位', $unit_arr)
			->addText('unit_measurement2', '输入计量单位[:请输入计量单位]')

			->addSelect('brand_id', '品牌', '请选择品牌', $brand_list_rel)
			
			// ->addSelect('class_id_arr', '选择商品分类', '请选择商品分类', model('ErpGoodsClass') -> where('pid',0) -> column('id,title'))
			
			->addLinkages('class_id_arr', '选择商品分类', '', 'erp_goods_class', 3, '', ['name' => 'title'])
			
			->addSelect('supplier_id', '供应商', '请选择供应商', $supplier_list_rel)

			->addImages_oss('pic1', '产品缩略图', '', '', '', '', '', ['size' => '500,500'])
			->addImages_oss('pic2', '产品详情图', '', '', '', '', '', ['size' => '500,500'])

			->addFormItems([ // 批量添加表单项
				['selectGroup', 'parameter', '商品参数', '', $groups, '', 'multiple'],
			])

			->addRadio('guige', '是否统一规格（单规格）', '', ['0' => '多规格', '1' => '统一规格'], 1)

			->addText('goods_huohao', '商品国际条形码[:请输入国际条形码]')
			->addHidden('goods_zhongliang', '')
			->addHidden('goods_tiji', '')
			->addText('purchase_price', '商品进价[:请输入价格]')
			->addText('goods_jiage', '商品售价[:请输入价格]')
			->addRadio('sku_status', '出售状态', '', ['0' => '不可售', '1' => '可售'], 1)

			->setTrigger('guige', 1, 'goods_huohao,goods_zhongliang,goods_tiji,goods_jiage,sku_status,purchase_price')

			->addCheckbox('specifications1', $speci_list[0]['title'], '',  $speci_list[0]['att_list'])
			->addCheckbox('specifications2', $speci_list[1]['title'], '', $speci_list[1]['att_list'])

			->setTrigger('guige', 0, 'specifications1,specifications2')
			//->isAjax(false)
            ->fetch();
	}

	/**
     *删除
     * @author baoshi
     * @return mixed
     * @throws \think\Exception
     */
    public function delete($ids = ''){

		$rel  = controller('Goodslogic', 'logic') -> goods_delete($ids);
		if($rel['code'] == 200){
			$this -> success('删除成功');
		}else{
			$this -> error('删除失败');
		}
		
	}

	 /**
     * 新增
     * @author shiqiang <976162041@qq.com>
     * @return mixed
     * @throws \think\Exception
     */
    public function add($pid = ''){  
		// 保存数据
		if ($this->request->isPost()) {
			//数据接收
			$data = $this->request->post('', null, 'trim');
			if($data['area'] > 0){
				$this->redirect('add_goods', ['goods_classtempid' => $data['area']]);
			}else{
				$this -> error('类目选择失败');
			}
			

		}

		$map = [];
		$map['pid'] = 0;
		$list_province=[];
		$list = model('ErpGoodsClassTemp') -> where($map) -> select();
		foreach ($list as $key => $value) {
			$list_province[$value['id']] = $value['title'];
		}//dump($list_province);die;
		//$list_province = ['gd' => '大连', 'gx' => '广西'];
        // 使用ZBuilder快速创建表单
        return ZBuilder::make('form')
            ->setPageTitle('选择类目')
            ->addFormItems([
				['linkage', 'province', '选择一级类目', '', $list_province, '', url('get_city'), 'city,area'],
				['linkage', 'city', '选择二级类目', '', '', '', url('get_area'), 'area'],
				['select', 'area', '选择三级类目'],
            ])
			->isAjax(false)	
            ->fetch();
	}
	
	//获取类目
    public function get_city($province = '')
    {
		$map = [];
		$map['pid'] = $province;
		$list = model('ErpGoodsClassTemp') -> where($map) -> select();
		$list_province = [];
		foreach ($list as $key => $value) {
			$list_province[] = [
				'key' => $value['id'],
				'value'	=> $value['title'],
			];
		}

        $arr['code'] = '1'; //判断状态
        $arr['msg'] = '请求成功'; //回传信息
        $arr['list'] = $list_province; //数据
        return json($arr);
    }
	
	//获取类目
    public function get_area($city = '')
    {
        $map = [];
		$map['pid'] = $city;
		$list = model('ErpGoodsClassTemp') -> where($map) -> select();
		$list_province = [];
		foreach ($list as $key => $value) {
			$list_province[] = [
				'key' => $value['id'],
				'value'	=> $value['title'],
			];
		}

        $arr['code'] = '1'; //判断状态
        $arr['msg'] = '请求成功'; //回传信息
        $arr['list'] = $list_province; //数据
        return json($arr);
    }

    /**
     * 获取详情
     */
    public function details($goods_id = '')
    {
        //参数接收
        /*$params = $this->getParams(0);//0 get 1 post
        $goods_id    = intval(isset($params["goods_id"]) ? $params["goods_id"] : 0);*/
        //数据验证
        //$Validate = validate('Goods', 'validate');
        if( $goods_id < 0 ){
            $this -> error('缺少商品Id');exit;
        }
        $res = controller('Goodslogic', 'logic') -> getGoodsInfo($goods_id);
        //数组整理
        $goodsInfo = [];
        $goodsInfo['goodsId'] = $res['data']['goodsId']?:'<em>&lt;No data available>&gt;</em>';//商品Id
        $goodsInfo['goodsName'] = $res['data']['goodsName']?:'<em>&lt;No data available>&gt;</em>';//商品名称
        $goodsInfo['goodsCode'] = $res['data']['goodsCode']?:'<em>&lt;No data available>&gt;</em>';//商品编码
        $goodsInfo['unitMeasurement'] = $res['data']['unitMeasurement']?:'<em>&lt;No data available>&gt;</em>';//商品计量单位
        if(isset($res['data']['supplierInfo']) && !empty($res['data']['supplierInfo'])){
            $goodsInfo['supplierInfo'] = $res['data']['supplierInfo']?:'<em>&lt;No data available>&gt;</em>';//商品
            if(isset($res['data']['supplierInfo']['title']) && !empty($res['data']['supplierInfo']['title'])) {
                $goodsInfo['supplierInfoTitle'] = $goodsInfo['supplierInfo']['title'] ?: '<em>&lt;No data available>&gt;</em>';//供应商
            }else{
                $goodsInfo['supplierInfoTitle'] = '<em>&lt;No data available>&gt;</em>';//供应商
            }
        }else{
            $goodsInfo['supplierInfo'] = '<em>&lt;No data available>&gt;</em>';//商品
            $goodsInfo['supplierInfoTitle'] = '<em>&lt;No data available>&gt;</em>';//供应商
        }

        $goodsInfo['brandInfo'] = $res['data']['brandInfo']['title']?:'<em>&lt;No data available>&gt;</em>';//
        //参数
        if(!empty($res['data']['parameterArr'])){
            foreach($res['data']['parameterArr'] as $kpa => $vpa){
                $parameterArr[] = $vpa['parameter_name'] .'：'.$vpa['attribute_name'];
            }
            $goodsInfo['parameterArr'][] = implode('</br>',$parameterArr);
        }else{
            $goodsInfo['parameterArr'][] = '';
        }
        //分类
        if(!empty($res['data']['classArr'])){
            foreach($res['data']['classArr'] as $kca => $vca){
                $goodsInfo['classArr'][] = $vca['class_name'];
            }
        }else {
            $goodsInfo['classArr'][] = '';
        }
        //规格
        if(!empty($res['data']['specificationsArr'])){
            foreach($res['data']['specificationsArr'] as $ksa => $vsa){
                if(!empty($vsa['specifications_attribute'])){
                    foreach ($vsa['specifications_attribute'] as $kkksa =>$vvvsa){
                        $specifications_title[$kkksa] = $vvvsa['attribute_title'];
                    }
                }else{
                    $specifications_title[] = '';
                }
                $goodsInfo['specificationsArr'][$ksa] = $vsa['specifications_title'].'：'.implode('，',$specifications_title);
            }
        }else {
            $goodsInfo['specificationsArr'][] = '';
        }

        //详细图
        if(!empty($res['data']['detailsImgArr'])){
            foreach($res['data']['detailsImgArr'] as $kci => $vci){
                $goodsInfo['detailsImgArr'][] = $vci['img_url'];
            }
            $goodsInfo['detailsImgArr'] = implode(',',$goodsInfo['detailsImgArr']);
        }else{
            $goodsInfo['detailsImgArr'] = '/static/admin/img/none.png';
        }
        //缩略图
        if(!empty($res['data']['coverImgArr'])){
            foreach($res['data']['coverImgArr'] as $kci => $vci){
                $goodsInfo['coverImgArr'][] = $vci['img_url'];
            }
            $goodsInfo['coverImgArr'] = implode(',',$goodsInfo['coverImgArr']);
        }else{
            $goodsInfo['coverImgArr'] = '/static/admin/img/none.png';
        }

        // 使用ZBuilder快速创建数据表格
        //参数
        foreach ( $goodsInfo['parameterArr'] as $kkpa =>$vvpa){
            $table_csgg[$kkpa] = [$vvpa]?:'<em>暂无参数</em>';
        }
        //分类
        foreach ( $goodsInfo['classArr'] as $kkca =>$vvca){
            $table_fl[$kkca] = [$vvca]?:'<em>暂无数据</em>';
        }
        //规格
        foreach ( $goodsInfo['specificationsArr'] as $kksa =>$vvsa){
            $table_gg[$kksa] = [$vvsa?:'<em>暂无规格</em>'];
        }


        $table_data = [
            ['<b style="font-size: 15px;color: #9A9A9A">商品基本信息[2]</b>'],
            ['<b>商品名称</b>',$goodsInfo['goodsName']],
            ['<b>商品编号</b>',$goodsInfo['goodsCode']],
            ['<b>商品计量单位</b>',$goodsInfo['unitMeasurement']],
            ['<b>商品品牌</b>',$goodsInfo['brandInfo']],
            ['<b>商品供应商</b>',$goodsInfo['supplierInfoTitle']],
            ['<b style="font-size: 15px;color: #9A9A9A">商品其他信息</b>[2]'],
            ['<b>商品参数</b>',$table_csgg],
            ['<b>商品分类</b>',$table_fl],
            ['<b>商品规格</b>',$table_gg],
        ];
        return ZBuilder::make('form')
            ->setPageTitle('详情信息') // 设置页面标题
            ->addFormItems([ // 批量添加表单项
                ['complexTable', 'list_user', '详情信息', $table_data, true]
            ])
            ->addGallery('coverImgArr', '产品相关缩略图集' , '', $goodsInfo['coverImgArr'])
            ->addGallery('detailsImgArr', '产品相关详细图集' , '', $goodsInfo['detailsImgArr'])
            ->hideBtn(['submit', 'back'])
            ->fetch();
        /*$this->assign('goodsInfo', $goodsInfo);
        return $this->fetch();*/
    }
	
}

